<template>
  <div class="filters-container">
    <!-- SQL类型过滤器 -->
    <div class="filter-group">
      <div class="filter-header">
        <h3>SQL语句类型</h3>
        <div class="select-all-option">
          <input 
            type="checkbox" 
            id="select-all-types"
            :checked="sqlTypesSelectAllState === 'all'"
            :indeterminate="sqlTypesSelectAllState === 'partial'"
            @change="toggleAllSqlTypes"
          >
          <label for="select-all-types">全选</label>
        </div>
      </div>
      <div class="filter-options">
        <div class="filter-option">
          <input 
            type="checkbox" 
            id="filter-select" 
            v-model="filters.types.select"
            @change="emitFilterChange"
          >
          <label for="filter-select">SELECT【使用{{ sqlTypeStats.select }}次】</label>
        </div>
        <div class="filter-option">
          <input 
            type="checkbox" 
            id="filter-insert" 
            v-model="filters.types.insert"
            @change="emitFilterChange"
          >
          <label for="filter-insert">INSERT【使用{{ sqlTypeStats.insert }}次】</label>
        </div>
        <div class="filter-option">
          <input 
            type="checkbox" 
            id="filter-update" 
            v-model="filters.types.update"
            @change="emitFilterChange"
          >
          <label for="filter-update">UPDATE【使用{{ sqlTypeStats.update }}次】</label>
        </div>
        <div class="filter-option">
          <input 
            type="checkbox" 
            id="filter-delete" 
            v-model="filters.types.delete"
            @change="emitFilterChange"
          >
          <label for="filter-delete">DELETE【使用{{ sqlTypeStats.delete }}次】</label>
        </div>
      </div>
    </div>
    
    <!-- 数据库表过滤器 -->
    <div class="filter-group">
      <div class="filter-header">
        <h3>数据库表</h3>
        <div class="select-all-option">
          <input 
            type="checkbox" 
            id="select-all-tables"
            :checked="tablesSelectAllState === 'all'"
            :indeterminate="tablesSelectAllState === 'partial'"
            @change="toggleAllTables"
          >
          <label for="select-all-tables">全选</label>
        </div>
      </div>
      <div class="table-filters">
        <div class="filter-options">
          <div 
            v-for="table in tables" 
            :key="table"
            class="filter-option"
          >
            <input 
              type="checkbox" 
              :id="`filter-table-${table}`"
              v-model="filters.tables[table]"
              @change="emitFilterChange"
            >
            <label :for="`filter-table-${table}`" class="table-label">
              <span class="table-name">{{ table }}</span>
              <span v-if="tableInfo[table]" class="table-details">
                <span v-if="tableInfo[table].comment" class="table-comment">
                  【{{ tableInfo[table].comment }}】
                </span>
                <span class="table-count">
                  - 使用{{ tableInfo[table].count }}次
                </span>
              </span>
              <span v-else-if="tableInfo[table] && tableInfo[table].loading" class="table-loading">
                (加载中...)
              </span>
            </label>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 过滤统计信息 -->
    <div class="filter-stats">{{ filterStats }}</div>
  </div>
</template>

<script>
import { extractTableNames } from '../utils/sqlFormatter'

export default {
  name: 'FilterSection',
  props: {
    tables: {
      type: Array,
      default: () => []
    },
    tableInfo: {
      type: Object,
      default: () => ({})
    },
    sqlStatements: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      filters: {
        types: {
          select: true,
          insert: true,
          update: true,
          delete: true
        },
        tables: {}
      },
      filterStats: ''
    }
  },
  watch: {
    tables: {
      immediate: true,
      handler(newTables) {
        // 初始化表过滤器
        newTables.forEach(table => {
          if (!(table in this.filters.tables)) {
            this.$set(this.filters.tables, table, true)
          }
        })
      }
    }
  },
  computed: {
    // SQL类型全选状态
    sqlTypesSelectAllState() {
      const types = this.filters.types
      const selectedCount = Object.values(types).filter(Boolean).length
      const totalCount = Object.keys(types).length
      
      if (selectedCount === 0) return 'none'
      if (selectedCount === totalCount) return 'all'
      return 'partial'
    },
    
    // 数据库表全选状态
    tablesSelectAllState() {
      const tables = this.filters.tables
      const selectedCount = Object.values(tables).filter(Boolean).length
      const totalCount = Object.keys(tables).length
      
      if (totalCount === 0) return 'none'
      if (selectedCount === 0) return 'none'
      if (selectedCount === totalCount) return 'all'
      return 'partial'
    },
    
    // 计算各SQL类型的使用次数（基于当前表过滤条件）
    sqlTypeStats() {
      const stats = {
        select: 0,
        insert: 0,
        update: 0,
        delete: 0
      }
      
      if (!this.sqlStatements || this.sqlStatements.length === 0) {
        return stats
      }
      
      // 获取当前激活的表列表
      const activeTables = Object.keys(this.filters.tables).filter(table => this.filters.tables[table])
      
      this.sqlStatements.forEach(stmt => {
        // 获取SQL类型
        const sqlType = this.getSQLType(stmt.processed)
        
        // 获取SQL涉及的表
        const involvedTables = extractTableNames(stmt.processed)
        
        // 如果SQL没有涉及任何表，或者涉及的表中有激活的表，则计入统计
        if (involvedTables.length === 0 || involvedTables.some(table => activeTables.includes(table))) {
          if (stats.hasOwnProperty(sqlType)) {
            stats[sqlType]++
          }
        }
      })
      
      return stats
    }
  },
  methods: {
    emitFilterChange() {
      this.$emit('filter-change', JSON.parse(JSON.stringify(this.filters)))
    },
    
    // 切换所有SQL类型的选中状态
    toggleAllSqlTypes() {
      const shouldSelectAll = this.sqlTypesSelectAllState !== 'all'
      Object.keys(this.filters.types).forEach(type => {
        this.filters.types[type] = shouldSelectAll
      })
      this.emitFilterChange()
    },
    
    // 切换所有数据库表的选中状态
    toggleAllTables() {
      const shouldSelectAll = this.tablesSelectAllState !== 'all'
      Object.keys(this.filters.tables).forEach(table => {
        this.filters.tables[table] = shouldSelectAll
      })
      this.emitFilterChange()
    },
    
    // 获取当前过滤器状态，用于ER图数据收集
    getCurrentFilters() {
      return {
        types: { ...this.filters.types },
        tables: { ...this.filters.tables }
      }
    },
    
    // 获取当前激活的SQL类型
    getActiveSqlTypes() {
      const activeTypes = []
      if (this.filters.types.select) activeTypes.push('SELECT')
      if (this.filters.types.insert) activeTypes.push('INSERT')
      if (this.filters.types.update) activeTypes.push('UPDATE')
      if (this.filters.types.delete) activeTypes.push('DELETE')
      return activeTypes
    },
    
    // 获取当前激活的数据库表
    getActiveTables() {
      const activeTables = []
      for (const [table, isActive] of Object.entries(this.filters.tables)) {
        if (isActive) {
          activeTables.push(table)
        }
      }
      return activeTables
    },
    
    // 获取SQL类型（与App.vue保持一致）
    getSQLType(sql) {
      const upperSQL = sql.toUpperCase().trim()
      if (upperSQL.startsWith('SELECT')) return 'select'
      if (upperSQL.startsWith('INSERT')) return 'insert'
      if (upperSQL.startsWith('UPDATE')) return 'update'
      if (upperSQL.startsWith('DELETE')) return 'delete'
      return 'other'
    }
  }
}
</script>

<style scoped>
.filters-container {
  background: #f3f4f6;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.filter-group {
  margin-bottom: 20px;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.filter-group h3 {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.select-all-option {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.select-all-option input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin-right: 6px;
  cursor: pointer;
}

.select-all-option label {
  cursor: pointer;
  color: #6b7280;
  font-weight: 500;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-option {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.filter-option input[type="checkbox"] {
  width: 18px;
  height: 18px;
  margin-right: 8px;
  cursor: pointer;
}

.filter-option label {
  cursor: pointer;
  color: #4b5563;
  font-size: 14px;
}

.filter-option:hover label {
  color: #1f2937;
}

.table-filters {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 10px;
  background: white;
}

.table-filters .filter-options {
  flex-direction: column;
  gap: 8px;
}

.filter-stats {
  text-align: right;
  font-size: 12px;
  color: #6b7280;
  margin-top: 8px;
}

/* 表名详情样式 */
.table-label {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.table-name {
  font-weight: 600;
  color: #374151;
}

.table-details {
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
}

.table-comment {
  color: #059669;
  font-style: italic;
}

.table-count {
  color: #7c3aed;
  font-weight: 500;
}

.table-loading {
  font-size: 12px;
  color: #9ca3af;
  font-style: italic;
}
</style>